﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using DevelopAssistant.Core.DBMS;
using DevelopAssistant.Core.ToolBox;
using DevelopAssistant.Service;
using ICSharpCode.WinFormsUI.Controls;
using ICSharpCode.WinFormsUI.Docking;

namespace DevelopAssistant.Core.ToolBar
{
    public partial class SnippetBar : DockContent
    {
        MainForm _MainForm;

        public SnippetBar()
        {
            InitializeComponent();
            LoadSnippetTreeData(null, string.Empty);
        }

        private void SnippetBar_Load(object sender, EventArgs e)
        {
            
        }

        private void LoadSnippetTreeData(TreeNode owner, string pid)
        {
            using (var db = NORM.DataBase.DataBaseFactory.Default)
            {
                string sqlText = "SELECT [ID]" +
                    ",[NAME]" +
                    ",[Pid]" +
                    ",[Snippet]" +
                    ",[IsShow]" +
                    ",[OrderIndex]" +
                    ",[Childs]" +
                    ",[Note]" +
                    ",[Define]" +
                    " FROM [T_SnippetTree]" +
                    " WHERE [IsShow]='1'";

                if (!string.IsNullOrEmpty(pid))
                {
                    sqlText += " AND [Pid]='" + pid + "'";
                }
                else
                {
                    sqlText += " AND [Pid]='0'";
                }

                sqlText += " ORDER BY [OrderIndex] ASC";


                DataTable snippetDataTable = db.GetDataSet(CommandType.Text, sqlText,null).Tables[0];

                foreach (DataRow dataRow in snippetDataTable.Rows)
                {
                    string cid = dataRow["ID"] + "";
                    string childs = dataRow["Childs"] + "";
                    string cpid = dataRow["Pid"] + "";

                    NTreeNode node = new NTreeNode();
                    node.Id = Int32.Parse(dataRow["ID"] + "");
                    node.Text = dataRow["NAME"] + "";
                    node.Snippet = dataRow["Snippet"] + "";
                    node.Pid = Int32.Parse(dataRow["Pid"] + "");
                    node.Note = dataRow["Note"] + "";
                    node.Define = dataRow["Define"] + "";
                    node.Childs = 0;

                    if (!string.IsNullOrEmpty(childs))
                    {
                        node.Childs = Int32.Parse(childs);
                    }

                    if (node.Childs > 0)
                    {
                        node.ImageIndex = 0;
                        node.SelectedImageIndex = 0;
                    }
                    else
                    {
                        node.ImageIndex = 2;
                        node.SelectedImageIndex = 2;
                    }

                    if (owner == null && string.IsNullOrEmpty(pid))
                        SnippetTree.Nodes.Add(node);

                    if (owner != null)
                    {                        
                        owner.Nodes.Add(node);
                        owner.ImageIndex = 1;
                        owner.SelectedImageIndex = 1;
                        if (owner.Level < 2)
                            owner.Expand();
                    }

                    LoadSnippetTreeData(node, cid);
                }

            }
        }

        private void SnippetTree_AfterCollapse(object sender, TreeViewEventArgs e)
        {
            e.Node.ImageIndex = 0;
            e.Node.SelectedImageIndex = e.Node.ImageIndex;
        }

        private void SnippetTree_AfterExpand(object sender, TreeViewEventArgs e)
        {
            e.Node.ImageIndex = 1;
            e.Node.SelectedImageIndex = e.Node.ImageIndex;
        }

        public void AddSqlSnippetCode(string ConnectionString, string ProviderName,string SnippetCode)
        {
            NTreeNode CurrentRootNode = null;
            switch (ProviderName)
            {
                case "System.Data.Sql":
                case "System.Data.SQL":
                    CurrentRootNode = (NTreeNode)this.SnippetTree.Nodes[2].Nodes[0].Nodes[0];
                    break;
                case "System.Data.Sqlite":
                case "System.Data.SQLite":
                    CurrentRootNode = (NTreeNode)this.SnippetTree.Nodes[2].Nodes[0].Nodes[1];
                    break;
                case "System.Data.PostgreSql":
                    CurrentRootNode = (NTreeNode)this.SnippetTree.Nodes[2].Nodes[0].Nodes[2];
                    break;
            }
            if (CurrentRootNode == null)
                return;

            MessageDialog messageBox = new MessageDialog("输入名称：");
            if (messageBox.ShowDialog(this).Equals(DialogResult.OK))
            {
                //添加到数据库
                using (var db = NORM.DataBase.DataBaseFactory.Default)
                {
                    string Name = messageBox.ResultText;
                    int Pid = CurrentRootNode.Id;
                    string Snippet = SnippetCode;
                    int IsShow = 1;
                    int OrderIndex = 0;
                    string Note = "SQL片段";
                    string Define = ConnectionString;
                    int Childs = 0;

                    StringBuilder strSql = new StringBuilder();
                    strSql.Append(" insert into T_SnippetTree ");
                    strSql.Append(" ( [NAME],[Pid],[Snippet],[IsShow],[OrderIndex],[Note],[Define],[Childs] ) ");
                    strSql.Append(" values(  '" + Name + "','" + Pid + "','" + Snippet + "'," + IsShow + ",'" + OrderIndex + "','" + Note + "','" + Define + "','" + Childs + "' ) ; ");
                    strSql.Append(System.Environment.NewLine);
                    strSql.Append(" update [T_SnippetTree] set Childs=Childs+1 where [ID]='" + Pid + "' ");
                    db.Execute(CommandType.Text, strSql.ToString(), null);
                }

                NTreeNode node = new NTreeNode();
                node.Pid = CurrentRootNode.Pid;
                node.Text = messageBox.ResultText;
                node.Snippet = SnippetCode;
                node.Note = "SQL片段";
                node.Define = ConnectionString;
                node.ImageIndex = 2;
                node.SelectedImageIndex = 2;
                CurrentRootNode.Nodes.Add(node);
                CurrentRootNode.Childs = CurrentRootNode.Childs + 1;

                this.SnippetTree.Refresh();

            }
            

        }

        private void SnippetTree_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            NTreeNode node = e.Node as NTreeNode;
            if (string.IsNullOrEmpty(node.Note))
                return;

            if (_MainForm == null)
                _MainForm = (MainForm)Application.OpenForms["MainForm"];

            if (_MainForm != null && node.Note == "SQL片段")
            {
                string sqlText = node.Snippet;

                //if (_MainForm.ConnectedDataBaseServer != null)
                //{
                //    NTreeNode parent_node = node.Parent as NTreeNode;
                //    if (_MainForm.ConnectedDataBaseServer.ConnectionString == node.Define &&
                //        _MainForm.ConnectedDataBaseServer.ProviderName == parent_node.Note)
                //    {
                //        QueryDocument query = new QueryDocument(_MainForm);
                //        _MainForm.AddNewContent(query, node.Text);
                //        query.SetSqlCommandText(sqlText);
                //    }                  
                //}

                QueryDocument query = new QueryDocument(_MainForm);
                _MainForm.AddNewContent(query, node.Text);
                query.SetSqlCommandText(sqlText);

            }
        }

        private void 刷新ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            NTreeNode node=(NTreeNode)this.SnippetTree.SelectedNode;
            node.Nodes.Clear();
            LoadSnippetTreeData(node, node.Id.ToString());
        }

        private void SnippetTree_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            NTreeNode node = (NTreeNode)e.Node;
            if (e.Button == MouseButtons.Right)
            {
                this.SnippetTree.SelectedNode = node;
            }
            if (node.Childs > 0)
            {
                删除ToolStripMenuItem.Visible = false;
            }
            else
            {
                删除ToolStripMenuItem.Visible = true;
            }
        }

        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            NTreeNode node = this.SnippetTree.SelectedNode as NTreeNode;
            NTreeNode parent_node = node.Parent as NTreeNode;

            if (node.Note != "SQL片段")
                return;

            if (MessageBox.Show(this,"确认要删除 " + node.Text + " 吗？ ","信息提示",
                MessageBoxButtons.OKCancel).Equals(DialogResult.OK))
            {
                using (var db = NORM.DataBase.DataBaseFactory.Default)
                {
                    string strSql = "DELETE FROM [T_SnippetTree] ";
                    strSql += "WHERE [ID]='" + node.Id + "' ; ";
                    strSql += System.Environment.NewLine;
                    strSql += "UPDATE [T_SnippetTree] SET Childs=Childs-1 WHERE [ID]='" + node.Pid + "'";
                    db.Execute(CommandType.Text, strSql, null);
                }

                parent_node.Nodes.Clear();
                LoadSnippetTreeData(parent_node, node.Pid.ToString());
                parent_node.Expand();
            }          

        }

        private void 编辑ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            NTreeNode node = this.SnippetTree.SelectedNode as NTreeNode;
            SnippetEdit snippetEdit = new SnippetEdit(node.Id,"Edit");
            if (snippetEdit.ShowDialog(this).Equals(DialogResult.OK))
            {
                NTreeNode root_node = (NTreeNode)this.SnippetTree.Nodes[0];
                NTreeNode parent_node = (NTreeNode)node.Parent;
                parent_node.Nodes.Clear();
                LoadSnippetTreeData(parent_node, parent_node.Id.ToString());
                parent_node.Expand();
            }
        }

        private void 添加ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            NTreeNode node = this.SnippetTree.SelectedNode as NTreeNode;           
            SnippetEdit snippetEdit = new SnippetEdit(node.Id, "Add");
            if (snippetEdit.ShowDialog(this).Equals(DialogResult.OK))
            {                
                node.Nodes.Clear();
                LoadSnippetTreeData(node, node.Id.ToString());
                node.Expand();
            }
        }
    
    }
}
